<?php

namespace app\common\model;

use think\Model;
use think\Db;

class Rechange extends Model
{
    //
    protected $insert = ['ctime'];
    
    public function user()
    {
        return $this->hasOne('User', 'id', 'user_id')->field(['id', 'avatar', 'nickname', 'password', 'mobile']);
    }
    
    public function setCtimeAttr()
    {
        return time();
    }
    
    public function pay($id, $code)
    {
        $rechange_info = $this->get($id);
        if(empty($rechange_info) || $rechange_info->status != '0') {
            throw new \Exception('订单支付失败');
        }
        $update_data = [
            'status'        =>  1,
            'payment_code'  =>  $code
        ];
        $res = $this->isUpdate(true)->save($update_data, ['id' =>  $rechange_info->id]);
        if($res) {
            $user_model = new User();
            $user_info = $user_model->field(['id', 'mobile', 'balance'])->where('id', $rechange_info->user_id)->find();
            if(empty($user_info)) {
                throw new \Exception('用户不存在');
            }
            $user_res = $user_model->where('id', $rechange_info->user_id)->setInc('balance', $rechange_info->amount);
            if($user_res) {
                $balance_log_model = new UserBalance();
                $balance_log_model->user_id     = $rechange_info->user_id;
                $balance_log_model->type        = 'add';
                $balance_log_model->balance     =  $user_info->balance+$rechange_info->amount;
                $balance_log_model->money       = $rechange_info->amount;
                $balance_log_model->save();
            } else {
                throw new \Exception('余额变更失败');
            }
        } else {
            throw new \Exception('订单更新失败');
        }
        doRequest(config('jshop.jpush_host'), ['id' => $id, 'method' => 'rechange']);
        return [
            'status' => true,
            'msg' => '订单支付成功',
            'data' => array()
        ];
    }
    
}
